<?php

namespace Common\Controller;

use Think\Controller;

class AdminBaseController extends Controller
{
    function __construct()
    {
        parent::__construct();
        if (!session('admin_id'))
            $this->redirect('/Admin/Login');
    }

    protected function createModel($model, $data)
    {
        if (!$model->create($data))
            $this->error($model->getError());
    }

    protected function getId()
    {
        return I('get.id') ? I('get.id') : $this->error('缺少 ID');
    }

    protected function delOneById($model, $id)
    {
        $req = $model->where(array('id' => $id))->delete();
        $req ? $this->success('删除成功！') : $this->error('删除失败！');
    }

    protected function displayPageList($model, $pageSize = 12, $where = array(), $order = 'id desc')
    {
        $count = $model->where($where)->count();
        $Page = new \Think\Page($count, $pageSize);
        $nowPage = I('p');
        $show = $Page->show();
        $this->assign('page', $show);
        $option = '';
        $pageSelect = '';
        for ($i = 1; $i <= $Page->totalPages; $i++) {
            if (intval($nowPage) == $i)
                $selected = 'selected = "selected"';
            else
                $selected = '';
            $option .= '<option value="' . $i . '" ' . $selected . '>' . $i . '</option>';
        }
        if($Page->totalPages > 1)
            $pageSelect .= '<form action="" method="get"><select name="p">' . $option . '</select><input type="submit" class="layui-btn layui-btn-normal layui-btn-xs" value="跳转"></form>';
        $this->assign('pageSelect', $pageSelect);
        $list = $model->where($where)->order($order)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        return $list;
    }


    protected function getData()
    {
        if (!IS_POST)
            $this->error('传输格式错误！');
        return I('post.');
    }

    protected function getSwitch($parm)
    {
        return $parm == "on" ? 1 : 0;
    }

    protected function logout()
    {
        session('admin_id',null);
        $this->success('登出成功！',U('/Admin/index'));
    }
}